package com.my.juc.lock;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @author zhupanlin
 * @version 1.0
 * @description: list集合线程不安全
 * @date 2024/3/5 16:50
 */


public class ThreadDemo4 {

    public static void main(String[] args) {
        // 创建ArrayList
        //List<String> list = new ArrayList<>();
        // Vector
        // Collections
        //List list1 = Collections.synchronizedList(list);
        // CopyOnWriteArrayList
        /*List<String> list = new CopyOnWriteArrayList<>();
        for (int i = 0; i < 30; i++) {
            new Thread(() -> {
                // 向集合中添加内容
                list.add(Thread.currentThread().getName());
                // 从集合中获取内容
                System.out.println("list = " + list);
            }, i + "").start();
        }*/
        
        // 演示HashSet
        // Set<String> set = new HashSet<>();
        /*Set<String> set = new CopyOnWriteArraySet<>();
        for (int i = 0; i < 30; i++) {
            new Thread(() -> {
                set.add(Thread.currentThread().getName());
                System.out.println(set);
            }, i +"").start();
        }*/
        
        // 演示HashMap
        //Map<String, String> map = new HashMap<>();
        Map<String, String> map = new ConcurrentHashMap<>();
        for (int i = 0; i < 30; i++) {
            new Thread(() -> {
                map.put(Thread.currentThread().getName() + "", "-" + Thread.currentThread().getName());
                System.out.println("map = " + map);
            }, i + "").start();
        }
    }
    
}
